package com.six.backend.service.impl;

import com.six.backend.dao.ToolDao;
import com.six.backend.pojo.*;
import com.six.backend.service.ToolService;
import com.six.backend.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author : 张重阳
 * @date : 2021-11-26 14:41
 */

@Service
public class ToolServiceImpl implements ToolService {

    @Autowired
    private ToolDao toolDao;

    @Override
    public List<Tool> getTools(Map map) {
        return toolDao.selectTools(map);
    }

    @Override
    public List<Tool> getAllTools(Map map) {
        return toolDao.selectAllTools(map);
    }


    @Override
    public List<Delphi> getDelphi(Integer toolId) {
        return toolDao.selectDelphi(toolId);
    }

    @Override
    public Integer postQuestionnaire(Questionnaire questionnaire) {
        if (toolDao.insertQuestionnaire(questionnaire) > 0) {
            return questionnaire.getId();
        }
        return 0;
    }

    @Override
    public boolean postQuestion(List<Question> topic,Integer questionnaireId) {
        boolean isOk = true;
        List<QuestionnaireQuestionRelation> relations = new ArrayList<>();
        for (Question question : topic) {
            if (question.getCreateTime() == null) {
                question.setCreateTime(new TimeUtil().getTime());
            }
            question.setUpdateTime(new TimeUtil().getTime());
            toolDao.insertQuestion(question);
            Integer questionId = question.getId();

            List<Choice> choices = question.getAnswers();

            QuestionnaireQuestionRelation questionnaireQuestionRelation = new QuestionnaireQuestionRelation();
            questionnaireQuestionRelation.setQuestionnaireId(questionnaireId);
            questionnaireQuestionRelation.setQuestionId(questionId);
            relations.add(questionnaireQuestionRelation);
            for (Choice choice : choices) {
                choice.setQuestionId(questionId);
            }
            if (toolDao.insertChoice(choices) == 0) {
                isOk = false;
            }
        }
        toolDao.insertQuestionRelations(relations);
        return isOk;
    }

    @Override
    public List<Questionnaire> getQuestionnaire(String name) {
        return toolDao.getQuestionnaire(name);
    }

    @Override
    public List<Tool> getUsingToolsByQuestionnaireId(Integer questionnaireId) {
        return toolDao.selectUsingToolsByQuestionnaireId(questionnaireId);
    }

    @Override
    public List<Question> getQuestion(Integer id) {
        List<Question> questions = toolDao.selectQuestionById(id);
        for (Question question : questions) {
            List<Choice> choices = toolDao.selectChoice(question.getId());
            question.setAnswers(choices);
        }
        return questions;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean deleteQuestionnaire(Integer id) {
        List<Question> questions = toolDao.selectQuestionById(id);
        Integer isDeleteQuestionnaire = toolDao.deleteQuestionnaire(id);
        Integer isDeleteRelation = toolDao.deleteRelation(id);
        List<Integer> choices = new ArrayList<>();
        List<Choice> options = toolDao.selectChoices(questions);
        for (Choice choice : options) {
            choices.add(choice.getId());
        }
        Integer isDeleteChoices =  toolDao.deleteChoices(choices);
        Integer isDeleteQuestion = toolDao.deleteQuestion(questions);
        return isDeleteQuestionnaire != 0 && isDeleteQuestion != 0 && isDeleteChoices != 0 && isDeleteRelation != 0;
    }

    @Override
    public List<User> getToolUserName(Integer toolId) {
        return toolDao.selectToolUserName(toolId);
    }

    @Override
    public Boolean endTool(Integer toolId) {
        return toolDao.endTool(toolId) > 0;
    }

    @Override
    public Integer endDelphi(Integer delphiId,Integer toolId,Integer turn) {
        // 封装属性
        Delphi delphi = new Delphi();
        delphi.setToolId(toolId);
        delphi.setTurn(turn);
        // 结束当前德尔菲问卷
        toolDao.endDelphi(delphiId);
        // 查询下一个德尔菲问卷的编号
        Integer nextDelphiId = toolDao.selectNextDelphiId(delphi);
        // 编号不为空则开启下一个问卷，为空则结束整个工具
        if (nextDelphiId != null) {
            toolDao.startDelphi(nextDelphiId);
        } else {
            toolDao.endToolByDelphiId(delphiId);
        }
        // 返回下一个德尔菲问卷的编号
        return nextDelphiId;
    }

    @Override
    public Boolean IsParticipant(String account,Integer delphiId) {
        return toolDao.selectIsParticipant(account,delphiId) == 1;
    }

    @Override
    public Boolean addUserAnswer(UserAnswer userAnswer) {
        String account = userAnswer.getAccount();
        Integer delphiId = userAnswer.getDelphiId();
        List<Integer> choiceId = userAnswer.getChoiceId();
        if (IsParticipant(account, delphiId)){
            return toolDao.insertUserAnswer(choiceId, account, delphiId) > 0 &&
                    toolDao.insertUserDelphi(account, delphiId) == 1;
        }
        return false;
   }

    @Override
    public List<UserFinishState> getFinishState(Integer delphiId) {
        return toolDao.selectFinishState(delphiId);
    }

    @Override
    public Questionnaire analyseUserAnswer(Integer delphiId) {

        // 获取问卷信息
        Questionnaire questionnaire = toolDao.selectQuestionnaireByDelphiId(delphiId);

        // 获取问题列表
        List<Question> questions = toolDao.selectQuestionById(questionnaire.getId());

        // 获取问卷的选项信息
        List<Choice> choices = toolDao.selectChoiceByDelphiId(delphiId);

        // 获取选项的统计信息
        List<Choice> counts = toolDao.countUserChoice(delphiId);

        // 为选项装配统计信息
        for (Choice choice : choices) {
            for (Choice count : counts) {
                if (choice.getId().equals(count.getId())) {
                    choice.setNums(count.getNums());
                }
            }
        }

        // 创建新的问题列表
        List<Question> questionList = new ArrayList<>();

        // 为每个问题装配选项信息
        for (Question question : questions) {
            List<Choice> choiceList = new ArrayList<>();
            for (Choice choice : choices) {
                if (choice.getQuestionId().equals(question.getId())) {
                    choiceList.add(choice);
                }
            }
            question.setAnswers(choiceList);
            questionList.add(question);
        }

        // 装配问卷
        questionnaire.setTopic(questionList);
        return questionnaire;
    }

    @Override
    public Integer useTool(RequestTool requestTool,String account) {
        Tool tool = new Tool();
        tool.setAccount(account);
        tool.setDate(new Date());
        tool.setState(1);
        //插入工具
        toolDao.insertTool(tool);
        Integer id = tool.getId();

        List<User> users = requestTool.getUsers();
        List<ToolUserRelation> relations = new ArrayList<>();
        for (User user : users) {
            ToolUserRelation toolUserRelation = new ToolUserRelation();
            toolUserRelation.setToolId(id);
            toolUserRelation.setUserAccount(user.getAccount());
            relations.add(toolUserRelation);
        }
        //插入工具推送人员联系表
        toolDao.insertToolUser(relations);

        List<Delphi> delphis = requestTool.getDelphis();
        for (Delphi delphi : delphis) {
            delphi.setToolId(id);
            delphi.setState(0);
        }
        for (Delphi delphi : delphis) {
            System.out.println(delphi);
        }
        //插入德尔菲问卷
        toolDao.insertDelphi(delphis);
        // 开启第一个德尔菲问卷
        toolDao.startFirstDelphi(id);
        return toolDao.selectFirstDelphi(id);
    }

    @Override
    public Integer startTool(Integer toolId) {
        toolDao.startTool(toolId);
        toolDao.startFirstDelphi(toolId);
        return toolDao.selectFirstDelphi(toolId);
    }

    @Override
    public Integer startAgenda(Integer toolId) {
        if (isPreviousAgendaFinished(toolId)) {
            toolDao.startTool(toolId);
            toolDao.startFirstDelphi(toolId);
            return toolDao.selectFirstDelphi(toolId);
        }
        return null;
    }


    @Override
    public Boolean isPreviousAgendaFinished(Integer toolId) {
        Integer agendaState = toolDao.selectPreviousAgendaState(toolId);
        System.out.println(agendaState);
        return agendaState == null ||
                agendaState == -1;
    }

    @Override
    public List<String> selectToolUserAccount(Integer id) {
        return toolDao.selectToolUserAccountByDelphi(id);
    }

    @Override
    public Boolean isToolPusher(Integer toolId,String account) {
        return account.equals(toolDao.getToolPusher(toolId));
    }
}
